<template>
    <div :class="`${theme}-publish-container`">
        <div :class="`${theme}-publish-content`">
            <n-form
                ref="formRef"
                :model="formData"
                label-placement="left"
                label-width="100"
                require-mark-placement="right-hanging"
            >
                <n-form-item label="发布状态" path="publishTime">
                    <div>
                        <n-switch v-model:value="appData.enable" :round="false" @change="handleToggleEnable" size="large">
                            <template #checked>
                                已发布
                            </template>
                            <template #unchecked>
                                未发布
                            </template>
                        </n-switch> &nbsp;&nbsp;
                        <n-popconfirm v-if="props.theme=='small'"    @positive-click="handlePositiveClick">
                            <template #trigger>
                                <n-button  :size="props.theme" ghost type="primary">
                                    <jb-icon :local="true" icon="ri:save-3-fill"></jb-icon> &nbsp;
                                    启用最新编排
                                </n-button>
                            </template>
                            确定要将最新编排的数据更新到应用上么?
                        </n-popconfirm>
                    </div>
                </n-form-item>
                <n-form-item label="访问地址" path="url">
                    <n-input-group>
                        <n-input v-model:value="formData.url" disabled placeholder="未发布无访问地址" readonly :size="props.theme"/>
                        <n-button type="primary" ghost @click="copyUrl" :size="props.theme">
                            <jb-icon :local="true" icon="ri:file-copy-2-line"></jb-icon>&nbsp;
                            复制
                        </n-button>
                        <n-button type="primary" ghost @click="openNewPage()" :size="props.theme">
                            <jb-icon :local="true" icon="oi:globe"></jb-icon> &nbsp;
                            打开新网址
                        </n-button>
                    </n-input-group>
                </n-form-item>

                <n-form-item label="二维码" path="qrcode">
                    <div class="flex flex-col items-center">
                        <div :class="`${theme}-qrcode-wrapper`">
                            <n-empty v-if="!formData.url" description="未发布暂无二维码"/>
                            <div v-else :class="`${theme}-qrcode-content`">
                                <n-qr-code id="qr-code" :value="formData.url"/>
                            </div>
                        </div>
                        <div class="mt-30">
                            <n-button strong secondary type="success" @click="handleDownloadQRCode()" :size="props.theme">
                                <jb-icon :local="true" icon="ri:download-2-line" height="18"></jb-icon> &nbsp;&nbsp;
                                下载二维码
                            </n-button>
                        </div>
                    </div>
                </n-form-item>
            </n-form>
        </div>
    </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {useMessage} from 'naive-ui'
import {JBoltApi} from "@/service/request/index.js";


const props = defineProps({
    appId: {
        type: String,
        required: true
    },
    theme: {
        type: String,
        required: true
    },
})
console.log('props', props)
const message = useMessage()

const formData = ref({
    publishTime: '',
    url: ``
})

// 复制URL
function copyUrl() {
    if (!formData.value.url) return
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(formData.value.url)
            .then(() => {
                message.success('复制成功');
            })
            .catch((err) => {
                console.error('复制失败:', err);
            });
    } else {
        console.error('当前浏览器不支持 Clipboard API');
        // 降级方案：使用旧的 execCommand 方法
        fallbackCopyText(formData.value.url);
    }
}

function fallbackCopyText(text) {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();
    try {
        document.execCommand('copy');
        message.success('复制成功');
    } catch (err) {
        console.error('复制失败（降级方案）:', err);
    }
    document.body.removeChild(textArea);
}

// 执行发布
async function handleToggleEnable() {
    const {result} = await JBoltApi.get(`/aiApp/toggleEnable/${props.appId}`);
    if (result) {
        formData.value.publishTime = new Date().toLocaleString()
        message.success("发布状态已更新")
        loadData()
    }
}

//加载app
const appData = ref({
    enable: false,
})

function loadData() {
    JBoltApi.tryGet(`/aiApp/getById/${props.appId}`).then(res => {
        appData.value = res.data
        formData.value.url = `${window.location.origin}/aiApp/${appData.value.sn}`
    })
}

//下载二维码
// 下载图片
const handleDownloadQRCode = () => {
    const canvas = document.querySelector('#qr-code canvas');
    if (canvas) {
        const url = canvas.toDataURL('image/png');
        const a = document.createElement('a');
        a.download = appData.value.name + Date.now() + '.png';
        a.href = url;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        message.success("二维码下载成功");
    } else {
        message.error("二维码下载失败");
    }
}
//打开新的网址
const openNewPage = () => {
    if (formData.value.url) {
        window.open(formData.value.url);
    } else {
        message.error("未发布无访问地址");
    }
}
//当theme是small的时候,才有这个按钮,启动最新编排到应用
function handlePositiveClick() {

    JBoltApi.tryGet(`/aiAppDesign/publish/${props.appId}`).then(
        res => {
            if (res) {
                message.success("发布成功")
            }
        }
    ).catch((err) => {
        console.error(err);
    });
}

onMounted(() => {
    if (props.appId) {
        loadData()
    }
});

</script>

<style scoped>
/**large-样式--------------------------------*/
.large-publish-container {
    padding: 20px;
}

.large-publish-content {
    background-color: var(--n-card-color);
    padding: 24px;
    border-radius: 8px;
}

.large-qrcode-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 200px;
    height: 200px;
}

.large-qrcode-content {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    width: 200px;
    height: 200px;
}

.large-qrcode-content :deep(canvas) {
    width: 200px !important;
    height: 200px !important;
}

/**large-样式--------------------------------*/

/**small-样式--------------------------------*/
.small-publish-container {
    padding-top: 20px;
}

.small-publish-content {
    background-color: var(--n-card-color);
    border-radius: 8px;
}

.small-qrcode-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 130px;
    height: 130px;
}

.small-qrcode-content {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    width: 130px;
    height: 130px;
}

.small-qrcode-content :deep(canvas) {
    width: 130px !important;
    height: 130px !important;
}

.small-qrcode-content :deep(.n-qr-code) {
    padding: 0px !important;
}

/**tiny-样式--------------------------------*/

</style>